import { defineEventHandler, readBody } from "h3";
import { updateUser } from "../../database/services/userService";

export default defineEventHandler(async (event) => {
  try {
    // 从认证中间件中获取用户信息
    const currentUser = event.context.user;
    
    if (!currentUser) {
      throw createError({
        statusCode: 401,
        statusMessage: "用户未认证"
      });
    }

    const body = await readBody(event);
    
    // 验证输入数据
    const allowedFields = ['name', 'email'];
    const updateData: any = {};
    
    for (const field of allowedFields) {
      if (body[field] !== undefined) {
        updateData[field] = body[field];
      }
    }
    
    // 验证邮箱格式
    if (updateData.email) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(updateData.email)) {
        throw createError({
          statusCode: 400,
          statusMessage: "邮箱格式不正确"
        });
      }
    }
    
    // 更新用户信息
    const success = await updateUser(currentUser.id, updateData);
    
    if (!success) {
      throw createError({
        statusCode: 500,
        statusMessage: "更新用户信息失败"
      });
    }
    
    return {
      success: true,
      message: "用户信息更新成功"
    };
  } catch (error) {
    console.error("更新用户信息时出错:", error);
    
    if (error.statusCode) {
      throw error;
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: "更新用户信息失败"
    });
  }
});
